//
//  RoomEditViewController.m
//  wAudioShare
//
//  Created by Anson on 14-11-16.
//  Copyright (c) 2014年 赵帅. All rights reserved.
//

#import "RoomEditViewController.h"
#import "Utitlity.h"
#import "RoomItemModel.h"
#import "AutomationCell.h"
#import "GlobalService.h"
#import "ChangeInfoDialog.h"
#import "RoomDeviceSelectListView.h"
#import "RemoteAirViewController.h"
#import "MMProgressHUD.h"
#import "CameraWebView.h"
#import "WISInterfaces.h"

//NSInteger PICKER_VIEW_ROOM_LIST_TAG = 1001;

@interface RoomEditViewController () <UIActionSheetDelegate, UIAlertViewDelegate, AutomationCellDelegate, changeDataDicDelegate, RoomDeviceSelectListViewDelegate>
{
    UIPickerView *_pickertView_RoomList;
}

@property (strong, nonatomic) RoomDeviceSelectListView *deviceSelectListView;
@property (strong, nonatomic) BottomView *bottomToolBar;

//@property (strong,nonatomic) NSMutableArray *attachDevicelList;//已分配到本房间的设备列表
@property (strong,nonatomic) NSMutableArray *deviceNotAttachedList;//还没有分配房间的设备列表
@property (nonatomic, strong) RoomItemModel *roomData;

@end

@implementation RoomEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    closeNextPage = YES;
    threadLoadData = NO;
    
    BottomView *bottomView = [self addBottomView];
    bottomView.btn_camera.hidden = NO;
    [bottomView.btn_camera addTarget:self action:@selector(openCamera) forControlEvents:UIControlEventTouchUpInside];
    bottomView.btn_all_power.hidden = NO;
    [bottomView.btn_all_power addTarget:self action:@selector(showMenu:) forControlEvents:UIControlEventTouchUpInside];
    self.bottomToolBar = bottomView;
    
    
    dataTableView.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - bottomView.frame.size.height);
    
    self.title = self.roomData.roomName;
    
    [self getAttachedDeviceList];
    
    [self getDeviceList];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - Http Request
- (void)getAttachedDeviceList {
    
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {

    NSString *loadStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Room.cgi?action=do_listdev&room=%ld", ipUrl, self.roomData.roomId];
    [Utitlity commonHTTPMethod:loadStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if (!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
        
        NSMutableArray *resultItem = [[NSMutableArray alloc] init];
        NSArray *devList = responseObject[@"data"];
        for (NSDictionary *item in devList) {            
            //NSInteger deviceType = [[item objectForKey:@"DeviceType"] integerValue];
            {
                [resultItem addObject:[NSMutableDictionary dictionaryWithDictionary:item]];
            }
        }
        
        self.rows = resultItem;
        [dataTableView reloadData];
        DLog(@"resultItem:%@",responseObject);
        
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        DLog(@"error:%@",error);
    }];
    }
}

- (void)getDeviceList {
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
    NSString *loadStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Get.cgi?Get=1", ipUrl];
    [Utitlity commonHTTPMethod:loadStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if (!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
        
        NSArray *devList = responseObject[@"data"];
        NSMutableArray *resultItem = [[NSMutableArray alloc] initWithCapacity:devList.count];
        for (NSDictionary *item in devList) {
            
            NSInteger roomId= [item[@"Room"] integerValue];
            if (roomId == 0)
            {//还没分配房间
                [resultItem addObject:[NSMutableDictionary dictionaryWithDictionary:item]];
            }
        }
        self.deviceNotAttachedList = resultItem;
        NSLog(@"resultItem:%@",responseObject);
        
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error:%@",error);
    }];
    }
}

//!向房间中添加一个设备
- (void)reqAddNewDeviceList:(NSArray *)deviceList {
    
    if (deviceList.count == 0) {
        return;
    }
    
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {

    [activity startAnimating];
    NSMutableArray *list = [NSMutableArray arrayWithCapacity:10];
    for (NSDictionary *item in deviceList) {
        [list addObject:item[@"ZID"]];
    }
    NSString *deviceIdList = [list componentsJoinedByString:@","];
        
        ASIFormDataRequest *formDataRequest = [ASIFormDataRequest requestWithURL:nil];
        NSString *encodedeviceIdList = [formDataRequest encodeURL:deviceIdList];

    
    NSString *loadStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Room.cgi?action=do_adddev&room=%ld&did=%@", ipUrl, self.roomData.roomId, encodedeviceIdList];
    [Utitlity commonHTTPMethod:loadStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [activity stopAnimating];
        
        if (!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
        
        NSDictionary *retJsonData = responseObject;
        if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
    
            [self.rows addObjectsFromArray:deviceList];
            [dataTableView reloadData];
        }
        
        NSLog(@"resultItem:%@",responseObject);
        
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error:%@",error);
    }];
    }
}

//!从房间中删除一个设备
- (void)reqDeleteDeviceList:(NSArray *)devList {
    
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {

    [activity startAnimating];
    
    NSDictionary *deviceData = [devList firstObject];
    NSString *deviceIds = deviceData[@"ZID"];
    
    NSString *loadStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Room.cgi?action=do_deldev&room=%ld&did=%@", ipUrl, self.roomData.roomId, deviceIds];
    [Utitlity commonHTTPMethod:loadStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [activity stopAnimating];
        
        if (!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
        
        NSDictionary *retJsonData = responseObject;
        if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
            [self.rows removeObject:deviceData];
            [dataTableView reloadData];
        }
        
        NSLog(@"resultItem:%@",responseObject);
        
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error:%@",error);
    }];
    }
}
//!清空房间中的设备
- (void)reqClearDevcies {
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {

    [activity startAnimating];

    NSString *loadStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Room.cgi?action=do_clear&room=%ld", ipUrl, self.roomData.roomId];
    [Utitlity commonHTTPMethod:loadStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [activity stopAnimating];
        
        if (!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
        
        NSDictionary *retJsonData = responseObject;
        if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
            [self.rows removeAllObjects];
            [dataTableView reloadData];
        }
        NSLog(@"resultItem:%@",responseObject);
        
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error:%@",error);
    }];
    }
}
//!房间更名
- (void)reqRoomeRename:(NSString *)newRoomName {
    
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {

    [activity startAnimating];
    
    ASIFormDataRequest *formDataRequest = [ASIFormDataRequest requestWithURL:nil];
    NSString *encodeRoomName = [formDataRequest encodeURL:newRoomName];
    
    NSString *loadStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Room.cgi?action=do_rename&room=%ld&name=%@", ipUrl, self.roomData.roomId, encodeRoomName];
    [Utitlity commonHTTPMethod:loadStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [activity stopAnimating];
        
        if (!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
        
        NSDictionary *retJsonData = responseObject;
        if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
            self.title = newRoomName;
            self.roomData.roomName = newRoomName;
            [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_ROOM_ITEM_CHANGE object:nil];
        }
        
        NSLog(@"resultItem:%@",responseObject);
        
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error:%@",error);
    }];
    }
}

#pragma mark -

- (void)setEditRoomData:(RoomItemModel *)data {
    _roomData = data;
}

- (void)setRoomList:(NSArray *)roomList {
    
    _roomDataList = roomList;
}


-(CGFloat)rowHeight
{
    return 76;
}

#pragma mark-UITableView
- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger row=[indexPath row];
    static NSString *AutomationCellIdentifier = @"AutomationCellIdentifier";
    AutomationCell *cell = (AutomationCell*)[dataTableView dequeueReusableCellWithIdentifier:AutomationCellIdentifier];
    if (cell==nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"AutomationCell" owner:self options:nil]lastObject];
        [cell initView];
        cell.adelegate= self;
        cell.curtainCtrlView.hidden = YES;
    }
    NSMutableDictionary *rowData = [self.rows objectAtIndex:row];
    
    //    NSMutableDictionary *muDic = [rowData mutableCopy];
    NSString *strUuid = [[GlobalService sharedInstance].curOperationDeviceUUID stringByReplacingOccurrencesOfString:@":" withString:@""];
    NSString *zidStr = rowData[@"ZID"];
    NSString *appStr = [NSString stringWithFormat:@"%@%@",strUuid,zidStr];
    [rowData setObject:appStr forKey:@"uuid"];
    [cell setCellData:rowData];
    
    NSInteger deviceType = [rowData[@"DeviceType"] integerValue];
    if (deviceType == 6) {
    //空调
        cell.icon.image = [UIImage imageNamed:@"icon_infrared"];
    }
    
    //	NSUInteger row=[indexPath row];
    //    return [self.rows objectAtIndex:row];
    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        NSDictionary *item = self.rows[indexPath.row];
        
        [self reqDeleteDeviceList:@[ item ]];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [dataTableView setEditing:NO animated:YES];
            
        });
        

    }
}

-(void)didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger row=[indexPath row];
    NSDictionary *rowData = [self.rows objectAtIndex:row];
    NSMutableDictionary *muDic = [rowData mutableCopy];
    NSString *strUuid = [[GlobalService sharedInstance].curOperationDeviceUUID stringByReplacingOccurrencesOfString:@":" withString:@""];
    NSString *zidStr = muDic[@"ZID"];
    NSString *appStr = [NSString stringWithFormat:@"%@r%@",strUuid,zidStr];
    [muDic setObject:appStr forKey:@"uuid"];
    NSString *rowStr = [NSString stringWithFormat:@"%ld",row];
    [muDic setObject:rowStr forKey:@"indexPath"];
    NSInteger kind = [[muDic objectForKey:@"DeviceType"] integerValue];
    if (kind == 6) {
        RemoteAirViewController *air = [[RemoteAirViewController alloc]init];
        air.Rdata = rowData;
        PersistableInfo *infoaaa = [DeviceListCell getRemoteInfo:muDic];
        air.title = infoaaa.name;
        //        air.title = [rowData objectForKey:@"Alias"];
        [self.navigationController pushViewController:air animated:YES];
    }
}

-(void)changeInfo:(NSDictionary *)data cell:(AutomationCell*)cell
{
    ChangeInfoDialog  *view = [[[NSBundle mainBundle] loadNibNamed:@"ChangeInfoDialog" owner:self options:nil]lastObject];
    view.delegate = self;
    [view initView];
    [view setData:data cell:cell];
    [view setRoomDataList:_roomDataList];
    [view setOriginalRoomData:self.roomData];
    [view pageStart];
}

#pragma mark - ChangeInfoDialog Delegate
- (void)changeDataDic:(NSDictionary *)dic
{
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        int i;
        for (i = 0; i < [self.rows count];i++)
        {
            NSDictionary *proDic = [self.rows objectAtIndex:i];
            if([dic[@"ZID"] isEqualToString:proDic[@"ZID"]])
            {
                @synchronized(self.rows){
                [dataTableView reloadData];
                }
                break;
            }
        }
        
        [MMProgressHUD showWithStatus:@"修改名字中...."];
        [MMProgressHUD dismissWithSuccess:@"修改名字成功"];
        
        [dataTableView reloadData];
        
    }
    else
    {
        [MMProgressHUD showWithTitle:@"修改名称错误" status:@"只能在局域网内进行修改"];
        [MMProgressHUD dismissAfterDelay:1];
    }
    
}

- (void)changeInfoDialogWithData:(NSDictionary *)dic changeToRoom:(RoomItemModel *)changeRoomData {
  
    if (self.roomData.roomId != changeRoomData.roomId) {
        
        [self.rows removeObject:dic];
        [dataTableView reloadData];
    }
}

#pragma mark - Button
- (void)showMenu:(UIButton *)sender {
    
    UIActionSheet *menu = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"选择设备" otherButtonTitles:@"删除设备", @"清空设备", @"修改名字", nil];
    [menu showFromRect:sender.frame inView:self.view animated:YES];
}

#pragma mark - UIActionSheet
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {
    
    if (actionSheet.tag == 100)
    {
        if (buttonIndex < [self.cameras count])
        {
            
            NSString *streamURL = [[self.cameras objectAtIndex:buttonIndex] objectForKey:@"VideoStream"];
            if (cameraView && ![cameraView.camURL isEqualToString:streamURL]) {
                [cameraView removeFromSuperview];
                cameraView = nil;
            }
            
            if (!cameraView) {
                cameraView = [[[NSBundle mainBundle] loadNibNamed:@"CameraWebView" owner:self options:nil]lastObject];
                cameraView.camURL = streamURL;
                cameraView.frame = CGRectMake(5, 5, 310, 235);
                [self.view addSubview:cameraView];
                dataTableView.frame = CGRectMake(0, 245, 320, self.view.frame.size.height - 245 - 60);
                [cameraView loadRequest];
            }
        }
        return;
    }
    
    
    switch (buttonIndex) {
        case 0:
        {
            if (!_deviceSelectListView) {
           
                _deviceSelectListView = [[RoomDeviceSelectListView alloc] initWithFrame:dataTableView.frame];
                _deviceSelectListView.customDelegate = self;
                [self.view addSubview:_deviceSelectListView];
            }else
                [self.view bringSubviewToFront:_deviceSelectListView];

            [_deviceSelectListView setDeviceDataSource:self.deviceNotAttachedList];
            self.bottomToolBar.btn_all_power.hidden = YES;
            self.bottomToolBar.btn_camera.hidden = YES;
            break;
        }
            
        case 1:
        {
            [dataTableView setEditing:YES animated:YES];
            break;
        }
            
        case 2:
        {
            [self reqClearDevcies];
            break;
        }
            
        case 3:
        {
            UIAlertView *prompt = [[UIAlertView alloc] initWithTitle:@"修改房间名称" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            prompt.alertViewStyle = UIAlertViewStylePlainTextInput;
            [prompt textFieldAtIndex:0].placeholder = @"名称";
            [prompt textFieldAtIndex:0].text = self.title;
            [prompt show];
            break;
        }
        default:
            break;
    }
    
}

#pragma mark - UIAlertView
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex == 1) {
        NSString *newRoomName = [alertView textFieldAtIndex:0].text;
        if (![newRoomName isEqualToString:self.title]) {
            [self reqRoomeRename:newRoomName];
        }
        
    }
}

#pragma mark - RoomDeviceSelectListView Delegat
- (void)roomDeviceSelectListView:(RoomDeviceSelectListView *)tableView confirmSelectDev:(NSArray *)dataList {

    [self reqAddNewDeviceList:dataList];
    [self.view sendSubviewToBack:tableView];
    self.bottomToolBar.btn_all_power.hidden = NO;
    self.bottomToolBar.btn_camera.hidden = NO;
}

#pragma mark - Camera
-(void)openCamera
{
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        [activity startAnimating];

        NSString *urlStr = [NSString stringWithFormat:@"http://%@/cgi-bin/IpCamera.cgi?OP=3",ipUrl];
        
        [Utitlity commonHTTPMethod:urlStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            [activity stopAnimating];
            self.cameras = responseObject;
            
            if (!responseObject) return;
            NSDictionary *retJsonData = responseObject;
            if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] )
            {
                
                NSArray *devList = [retJsonData objectForKey:@"data"];
                self.cameras = devList;
                
                UIActionSheet *menu = [[UIActionSheet alloc]
                                       initWithTitle: @"请选择"
                                       delegate:self
                                       cancelButtonTitle:nil
                                       destructiveButtonTitle:nil
                                       otherButtonTitles:nil];
                menu.tag = 100;
                
                
                
                for (NSDictionary *dict in self.cameras)
                {
                    [menu addButtonWithTitle:[dict objectForKey:@"Alias"]];
                }
                [menu addButtonWithTitle:@"取消"];
                menu.cancelButtonIndex = menu.numberOfButtons-1;
                NSLog(@"111111");
                [menu showInView:self.view];
            }
            else
            {
                [self openCamera];
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }else
    {
        [activity startAnimating];

        [[CMDDataProcessor sharedInstance] sendCMDId:WIS_CMD_V2_CMD_CAM_LIST_GET cmdLength:32 withData:(void *)[[[GlobalInfo sharedInstance] getUniqueID] UTF8String] callRecivedBlock:^(id data) {
            
            [activity stopAnimating];
            self.cameras = data;
            
            if (!data) return;
            NSDictionary *retJsonData = data;
            if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
                
                NSArray *devList = [retJsonData objectForKey:@"data"];
                self.cameras = devList;
                
                UIActionSheet *menu = [[UIActionSheet alloc]
                                       initWithTitle: @"请选择"
                                       delegate:self
                                       cancelButtonTitle:nil
                                       destructiveButtonTitle:nil
                                       otherButtonTitles:nil];
                menu.tag = 100;
                NSMutableArray *btnArr = [[NSMutableArray alloc] init];
                for (NSDictionary *dict in self.cameras)
                {
                    [btnArr addObject:[dict objectForKey:@"Alias"]];
                }
                for (NSString *str in btnArr) {
                    [menu addButtonWithTitle:str];
                }
                [menu addButtonWithTitle:@"取消"];
                menu.cancelButtonIndex = menu.numberOfButtons-1;
                [menu showInView:self.view];
            }
        }];
    }
}

@end
